import React, { Component } from 'react';
import {
    View, Text, TouchableOpacity, StyleSheet, ScrollView, Image, Dimensions
} from 'react-native';
import { connect } from 'react-redux';
import * as balanceAction from '../actions/balance';

import { TABBAR_LABEL, ROUTERMAP, Global, API_MAP } from '../util/constants';
import CommonTitleBar from "../components/CommonTitleBar";
import BalanceRecord from '../components/BalanceRecordItem';
import { scaleSize, scaleFontSize } from '../util/size';
import icons from '../util/icons';
import { utilGetAvailableByCoinType } from '../util/balanceUtil';
import { INavigation, IReduxMarketInfo } from '../interface';
import { request } from '../util';
import { utilGetAmountToByCoinType } from '../util/marketUtil';

const { height: deviceHeight, width: deviceWidth } = Dimensions.get('window');

interface IProps {
    balance: any,
    market: IReduxMarketInfo,
    navigation: INavigation
}

interface IState {
    activeTab: string,
    balanceRecord: Array<any>,
    available: string | number
}


class BalanceInfo extends Component<IProps, IState> {
    constructor(props) {
        super(props);
        this.state = {
            activeTab: 'BTC',
            balanceRecord: [],
            available: 0.000000
        }
    }

    componentDidMount() {
        const { navigation } = this.props;
        const type: string = navigation.getParam('type', 'BTC');
        const available = navigation.getParam('available', 0);
        this.loadBalanceRecordInfo();
        this.setState({
            activeTab: type,
            available: available,
        })
    }

    turnToPage = (pageName: string, params?: Object) => {
        this.props.navigation.navigate(pageName, params);
    }


    updateActiveTab = (activeTab: string) => {
        this.setState({ activeTab })
    }

    renderTopOptionBtn = () => {
        let { activeTab } = this.state;
        const keys = ['BTC', 'ETH', 'EOS', 'CXP'];
        return (
            <View style={{
                display: 'flex',
                flexDirection: 'row',
                justifyContent: 'space-between',

            }}>
                {
                    keys.map((v, index) => {
                        if (v === activeTab) {
                            return (
                                <TouchableOpacity style={[styles.activeTopOptionBtn]} key={`topOptionBtn-${index}`} onPress={() => {
                                    this.updateActiveTab(v)
                                }}>
                                    <Text style={[styles.activeTopOptionBtnText]}>{v}</Text>
                                </TouchableOpacity>
                            )
                        } else {
                            return (
                                <TouchableOpacity style={[styles.inactiveTopOptionBtn]} key={`topOptionBtn-${index}`} onPress={() => {
                                    this.updateActiveTab(v)
                                }}>
                                    <Text style={[styles.inactiveTopOptionBtnText]}>{v}</Text>
                                </TouchableOpacity>
                            )
                        }
                    })
                }
            </View>
        )
    }

    loadBalanceRecordInfo = () => {
        request(API_MAP.balanceRecord, {
            method: 'get',
            data: {
                page: 1,
                limit: 3,
            }
        }, false, (err, res) => {
            if (res.retCode == '00') {
                let {list = []} = res.data;
                this.setState({balanceRecord: list});
            }
        })
    }

    renderTransactionRecord = () => {
        let { balanceRecord } = this.state;
        // balanceRecord = [
        //     { time: '10:59:59 18/07/07', type: '充币', op: '+2.0 BTC' },
        //     { time: '10:59:59 18/07/07', type: '充币', op: '+2.0 BTC' },
        //     { time: '10:59:59 18/07/07', type: '充币', op: '+2.0 BTC' }
        // ]
        return (
            <View >
                <ScrollView>
                    {
                        balanceRecord.map((v, index) => {
                            return (
                                <BalanceRecord {...v} key={`balanceRecord-${index}`} />
                            )
                        })
                    }
                </ScrollView>
            </View>
        )
    }


    render() {
        const { activeTab: coinType } = this.state;
        let available = utilGetAvailableByCoinType(this.props.balance, coinType);
        let amountTo = utilGetAmountToByCoinType(this.props.market, coinType);
        amountTo = Number((amountTo * available).toFixed(4));
        return (
            <View>
                <CommonTitleBar nav={this.props.navigation} back={true} backgroundColor={'white'} />
                <View style={{
                    display: 'flex',
                    height: deviceHeight - Global.titleBarHeight,
                    flexDirection: 'column',
                    justifyContent: 'space-between',
                    // alignItems: 'center',
                    // flexDirection: 'column',
                }}>
                    <View>
                        <View style={{
                            padding: scaleSize(20),
                            height: scaleSize(206),
                            backgroundColor: '#FFFFFF'
                        }}>
                            {
                                this.renderTopOptionBtn()
                            }
                            <View style={{
                                display: 'flex',
                                flexDirection: 'row',
                                marginTop: scaleSize(16),
                                marginLeft: scaleSize(16)
                            }}>
                                <Text style={{
                                    height: scaleSize(41),
                                    minWidth: scaleSize(180),
                                    maxWidth: scaleSize(250),
                                    textAlign: 'left',
                                    fontFamily: 'Helvetica',
                                    fontSize: scaleSize(34),
                                    color: '#4A4A4A',
                                }}> {available} </Text>
                                <Text style={{
                                    marginLeft: scaleSize(8),
                                    fontFamily: 'PingFangSC-Medium',
                                    fontSize: scaleSize(16),
                                    color: '#4A4A4A',
                                    textAlign: 'center',
                                    textAlignVertical: 'bottom',
                                    alignSelf: 'center',
                                    // alignItems: 'flex-end'
                                }}>{this.state.activeTab}</Text>
                            </View>
                            <View style={{
                                marginTop: scaleSize(4),
                                marginLeft: scaleSize(16)
                            }}>
                                <Text style={{
                                    opacity: 0.65,
                                    fontFamily: 'Helvetica',
                                    fontSize: scaleFontSize(16),
                                    color: '#9B9B9B',
                                }}>
                                    ≈ {amountTo} CNY
                            </Text>
                            </View>
                        </View>
                        <View style={{
                            marginTop: scaleSize(4),
                            backgroundColor: '#FFFFFF'
                        }}>
                            <View style={[
                                styles.padding,
                                {
                                    paddingTop: scaleSize(16),
                                    display: 'flex',
                                    flexDirection: 'row',
                                    justifyContent: 'space-between',
                                    height: scaleSize(50),
                                }
                            ]}>
                                <Text style={[
                                    {
                                        fontFamily: 'PingFangSC-Regular',
                                        fontSize: scaleSize(14),
                                        color: '#4A4A4A',
                                    }
                                ]}>
                                    财务记录
                                </Text>
                                <Text style={[
                                    {
                                        fontFamily: 'PingFangSC-Regular',
                                        fontSize: scaleFontSize(14),
                                        color: '#9B9B9B',
                                    }
                                ]} onPress={() => {
                                    this.turnToPage(ROUTERMAP.balanceRecord)
                                }}>
                                    全部
                                </Text>
                            </View>
                            {
                                this.renderTransactionRecord()
                            }
                        </View>

                    </View>
                    <View style={[
                        {
                            width: deviceWidth,
                            display: 'flex',
                            justifyContent: 'space-around',
                            flexDirection: 'row',
                            paddingTop: scaleSize(20),
                            height: scaleSize(102),
                            backgroundColor: '#FFFFFF',
                        }
                    ]}>
                        <TouchableOpacity activeOpacity={0.9} onPress={
                            () => {
                                this.turnToPage(ROUTERMAP.depositandwithdraw, {
                                    tab: 'deposit',
                                    coinType: coinType
                                })
                            }
                        }>
                            <Image source={icons.balanceInfoDeposit} style={styles.buttonImage} />
                            <Text style={styles.buttonText} >充币</Text>
                        </TouchableOpacity>


                        <TouchableOpacity activeOpacity={0.9} onPress={
                            () => {
                                this.turnToPage(ROUTERMAP.depositandwithdraw, {
                                    tab: 'withdraw',
                                    coinType: coinType
                                })
                            }
                        }>
                            <Image source={icons.balanceInfoExtract} style={styles.buttonImage} />
                            <Text style={styles.buttonText}>提币</Text>
                        </TouchableOpacity>

                        <TouchableOpacity activeOpacity={0.9} onPress={() => {
                            this.turnToPage(ROUTERMAP.transaction, {
                                coinType: `${coinType}/USDT`,
                                opStatus: 'buy'
                            })
                        }}>
                            <Image source={icons.balanceInfoExchange} style={styles.buttonImage} />
                            <Text style={styles.buttonText} >交易</Text>
                        </TouchableOpacity>

                    </View>
                </View>
            </View>
        )
    }

}

export default connect(
    (state) => ({
        balance: state.balance,
        market: state.market,
    }),
    (dispatch) => ({
        updateBalanceInfo: (data) => dispatch(balanceAction.updateBalanceInfo(data)),
    })
)(BalanceInfo);

const styles = StyleSheet.create({
    padding: {
        paddingLeft: scaleSize(20),
        paddingRight: scaleSize(20),
    },
    activeTopOptionBtn: {
        backgroundColor: '#4869EE',
        height: scaleSize(33),
        width: scaleSize(67),
        // borderRadius: scaleSize(100),
    },
    activeTopOptionBtnText: {
        color: 'white',
        height: scaleSize(33),
        lineHeight: scaleSize(33),
        width: scaleSize(67),
        fontFamily: 'PingFangSC-Semibold',
        fontSize: scaleSize(18),
        textAlign: 'center',
    },
    inactiveTopOptionBtn: {
        backgroundColor: 'white',
        height: scaleSize(33),
        width: scaleSize(67),
        // borderRadius: scaleSize(100),
        borderWidth: 1,
        borderColor: '#E2E2E2'
    },
    inactiveTopOptionBtnText: {
        height: scaleSize(33),
        lineHeight: scaleSize(33),
        width: scaleSize(67),
        fontFamily: 'PingFangSC-Regular',
        color: '#C5C5C5',
        fontSize: scaleSize(18),
        textAlign: 'center'
    },
    buttonImage: {
        width: scaleSize(34),
        height: scaleSize(34),
    },
    buttonText: {
        marginTop: scaleSize(2),
        fontFamily: 'PingFangSC-Regular',
        fontSize: scaleSize(10),
        color: '#C6C6C6',
        textAlign: 'center',
    }
})